package com.guoxue.action.back;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.guoxue.action.front.BaseAction;
import com.guoxue.domain.*;
import com.guoxue.model.BookConfig;
import com.guoxue.model.ChapterConfig;
import com.guoxue.model.ExplainConfig;
import com.guoxue.model.PlanConfig;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.IChapterConfigService;
import com.guoxue.service.ICoinsService;
import com.guoxue.service.IDistrictService;
import com.guoxue.service.IExpertReadingService;
import com.guoxue.service.IExplainConfigService;
import com.guoxue.service.IPlanChapterConfigService;
import com.guoxue.service.IPlanConfigService;
import com.guoxue.service.IPropertyConfigService;
import com.guoxue.service.IPublishLogsService;
import com.guoxue.service.IRecordConfigService;
import com.guoxue.service.IResourceService;
import com.guoxue.service.IShopConfigService;
import com.guoxue.service.IStageConfigService;
import com.guoxue.service.IStoryConfigService;
import com.guoxue.service.IUpdateService;
import com.guoxue.service.IUploadLogsService;
import com.guoxue.util.ExcelUtil;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.MD5Util;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;

/**
 * 配置文件上传等相关处理
 * @author young
 *
 */
@Controller
@RequestMapping("File")
public class UploadLogsAction extends BaseAction{
	
	@Resource
	private IUploadLogsService uploadLogsService;
	@Resource
	private ExcelUtil util;
	@Resource
	private IRecordConfigService recordServcie;
	@Resource
	private IBookConfigService bookServcie;
	@Resource
	private IChapterConfigService chapterService;
	@Resource
	private IExpertReadingService expertService;
	@Resource
	private IExplainConfigService explainService;
	@Resource
	private IPlanConfigService planConfigService;
	@Resource
	private IPropertyConfigService propertyConfigService;
	@Resource
	private IDistrictService districtService;
	@Resource
	private IStageConfigService stageConfigService;
	@Resource
	private IStoryConfigService storyConfigService;
	@Resource
	private IPublishLogsService publishService;
	@Resource
	private IUpdateService updateService;
	@Resource
	private IResourceService resourceService;
	@Resource
	private IPlanChapterConfigService PlanChapterService;
	@Resource
	private OSSUtil oss;
	@Resource
	private IShopConfigService shopConfigService;
	@Resource
	private ICoinsService coinsService;
	/**
	 * 各配置文件上传
	 * @param req
	 * @param resp
	 * @param file
	 * @param type
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public JSON uploadFiles(HttpServletRequest req, HttpServletResponse resp, MultipartFile file, String type){
		try {
			String fileName = file.getOriginalFilename();
			String relName = OtherUtils.UuidUtils().substring(15,31);
			//UploadLogsVo logs = new UploadLogsVo(OtherUtils.getCurrentDate(),fileName,reName,"",reName);
			UploadLogsVo logs = new UploadLogsVo();
			logs.setUploadDate(OtherUtils.getCurrentDate());
			logs.setFileName(fileName);
			logs.setRelName(relName);
			logs.setType("");
			logs.setPath(relName);			
			oss.putObject(bucket, relName, file.getInputStream());   //存放OSS
			util.init(file.getInputStream(), logs.getFileName().split("\\.")[1]);
			if (type.equals("tapesConfig")){
				List<RecordConfigVo> ls = util.bindToModels(RecordConfigVo.class, false);  //解析装换为对应bean
				for (RecordConfigVo rc:ls){
					if (rc.getWordId()<=0){
						continue;
					}
					SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.S");
					Date d = sdf.parse(rc.getBeginTime());
					Date d2 = sdf.parse(rc.getEndTime());
					if (d.getTime()>d2.getTime()){
						return Message(ERROR, "对应ID:"+rc.getWordId()+"开始时间（beginTime）大于结束时间（endTime）", null);
					}
					if (isEmpty(rc.getFile())){
						return Message(ERROR, "对应ID:"+rc.getWordId()+"对应File为空", null);
					}
					recordServcie.saveRecordConfig(rc);
				}
			} else if (type.equals("bookConfig")){
				List<BookConfigVo> ls = util.bindToModels(BookConfigVo.class, false);
				for (BookConfigVo bc:ls){
					if (bc.getBookId()<=0){
						continue;
					}
					if (isEmpty(bc.getBookName())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"BookName不能为空", null);
					}
					if (isEmpty(bc.getPicIcon())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"PicIcon不能为空", null);
					}
					if (isEmpty(bc.getPicTile())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"PicTile不能为空", null);
					}
					if (isEmpty(bc.getPicX())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"PicX不能为空", null);
					}
					if (isEmpty(bc.getPicY())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"PicY不能为空", null);
					}
					if (isEmpty(bc.getPlanPic())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"PlanPic不能为空", null);
					}
					if (isEmpty(bc.getReadPic())){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"ReadPic不能为空", null);
					}
					if (bc.getBeginPlanId()>bc.getEndPlanId()){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"起始计划ID（BeginPlanId）大于结束计划ID（EndPlanId）", null);
					}
					if (bc.getBeginChapterId()>bc.getEndChapterId()){
						return Message(ERROR, "对应ID:"+bc.getBookId()+"起始章节ID（BeginChapterId）大于结束章节ID（EndChapterId）", null);
					}
					bookServcie.saveBookConfig(bc);
				}
			}  else if (type.equals("chapterConfig")){
				List<ChapterConfigVo> ls = util.bindToModels(ChapterConfigVo.class, false);
				for (ChapterConfigVo cc:ls){
					if (cc.getChapterId()<=0){
						continue;
					}
					if (isEmpty(cc.getChapterName())){
						return Message(ERROR, "对应ID:"+cc.getChapterId()+"ChapterName不能为空", null);
					}
					if (cc.getEndWordId()==0){
						return Message(ERROR, "对应ID:"+cc.getChapterId()+"EndWordId不能为空或0", null);
					}
					if (cc.getBeginWordId()==0){
						return Message(ERROR, "对应ID:"+cc.getChapterId()+"BeginWordId不能为空或0", null);
					}
					if (cc.getEndWordId()<cc.getBeginWordId()){
						return Message(ERROR, "对应ID:"+cc.getChapterId()+"BeginWordId大于EndWordId", null);
					}
					chapterService.saveChapterConfig(cc);
				}
			} else if (type.equals("masterConfig")){
				List<ExpertReadingVo> ls = util.bindToModels(ExpertReadingVo.class, false);
				for (ExpertReadingVo er: ls){
					if (er.getWorkId()<=0){
						continue;
					}
					if(isEmpty(er.getBookName())){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"BookName不能为空", null);
					}
					if (isEmpty(er.getIntroduced())){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"Introduced不能为空", null);
					}
					if (isEmpty(er.getWorkReader())){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"WorkReader不能为空", null);
					}
					if (isEmpty(er.getWriter())){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"Writer不能为空", null);
					}
					if (er.getBeginChapterId()==0){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"BeginChapterId不能为空", null);
					}
					if (er.getEndChapterId()==0){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"EndChapterId不能为空", null);
					}
					if (er.getBeginChapterId()>er.getEndChapterId()){
						return Message(ERROR, "对应ID:"+er.getWorkId()+"EndChapterId小于BeginChapterId", null);
					}
					expertService.saveExpertReading(er);
					}
			} else if (type.equals("meanConfig")){
				List<ExplainConfigVo> ls = util.bindToModels(ExplainConfigVo.class, false);
				for (ExplainConfigVo ec: ls){
					if (ec.getExplainId()<=0){
						continue;
					}
					explainService.saveExplain(ec);
				}
			} else if (type.equals("planConfig")){
				List<PlanConfigVo> ls = util.bindToModels(PlanConfigVo.class, false);
				for (PlanConfigVo pc: ls){
					if (pc.getPlanId()<=0){
						continue;
					}
					if (pc.getCount()==0){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"count不能为0或空", null);
					}
					if (pc.getPlanChapterdx()==0){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanChapterdx不能为0或空", null);
					}
					if (pc.getPlanChapterdy()==0){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanChapterdy不能为0或空", null);
					}
					if (pc.getPlanChapterdx()>pc.getPlanChapterdy()){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanChapterdx不能大于PlanChapterdy", null);
					}
					if (isEmpty(pc.getPlanName())){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanName不能为空", null);
					}
					if (isEmpty(pc.getPlanTitle())){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanTitle不能为空", null);
					}
					if (isEmpty(pc.getPlanType())){
						return Message(ERROR, "对应ID:"+pc.getPlanId()+"PlanType不能为空", null);
					}
					planConfigService.savePlanConfig(pc);
				}
			} else if (type.equals("propConfig")){
				List<PropertyConfigVo> ls = util.bindToModels(PropertyConfigVo.class, false);
				for (PropertyConfigVo pc: ls){
					if (pc.getPropId()<=0){
						continue;
					}
					if (isEmpty(pc.getPropType())){
						return Message(ERROR, "对应ID:"+pc.getPropId()+"PropType为空", null);
					}
					if (isEmpty(pc.getPropIcon())){
						return Message(ERROR, "对应ID:"+pc.getPropId()+"PropPropIcon为空", null);
					}
					propertyConfigService.savePropertyConfig(pc);
				}
			} else if (type.equals("regionConfig")){
				List<DistrictVo> ls = util.bindToModels(DistrictVo.class, false);
				for (DistrictVo dt: ls){
					districtService.saveDistrict(dt);
				}
			} else if (type.equals("levelConfig")){
				List<StageConfigVo> ls = util.bindToModels(StageConfigVo.class, false); 
				for (StageConfigVo sc: ls){
					if (sc.getStageId()<=0){
						continue; 
					}
					if (isEmpty(sc.getStageName())){
						return Message(ERROR, "对应ID:"+sc.getStageId()+"StageName为空", null);
					}
					if (isEmpty(sc.getStagePicture())){
						return Message(ERROR, "对应ID:"+sc.getStageId()+"StagePicture为空", null);
					}
					stageConfigService.saveStageConfig(sc);
				}
			} else if (type.equals("storyConfig")){
				List<StoryConfigVo> ls = util.bindToModels(StoryConfigVo.class, false);
				for (StoryConfigVo sc: ls){
					if (sc.getStoryId()<=0){
						continue;
					}
					if (isEmpty(sc.getTitle())){
						return Message(ERROR, "对应ID:"+sc.getStoryId()+"Title为空", null);
					}
					if (isEmpty(sc.getContent())){
						return Message(ERROR, "对应ID:"+sc.getStoryId()+"Content为空", null);
					}
					storyConfigService.saveStoryConfig(sc);
				}
			} else if (type.equals("shopConfig")){
				List<ShopConfigVo> ls = util.bindToModels(ShopConfigVo.class, false);
				for (ShopConfigVo sc: ls){
					if (sc.getId()<=0){
						continue;
					}
					if (sc.getBuyLimit()==0){
						return Message(ERROR, "对应ID:"+sc.getId()+"BuyLimit不能为0或空", null);
					}
					if (sc.getPropId()==0){
						return Message(ERROR, "对应ID:"+sc.getId()+"PropId不能为0或空", null);
					}
					shopConfigService.saveShopConfig(sc);
				}
			} else if (type.equals("planChapterConfig")){
				List<PlanChapterConfigVo> ls = util.bindToModels(PlanChapterConfigVo.class, false);
				for (PlanChapterConfigVo pc: ls){
					if (pc.getPlanChapterId()<=0){
						continue;
					}
					if (isEmpty(pc.getPlanChapterName())){
						return Message(ERROR, "对应ID:"+pc.getPlanChapterId()+"ChapterName不能为空", null);
					}
					if (pc.getEndWordId()==0||pc.getBeginWordId()==0){
						return Message(ERROR, "对应ID:"+pc.getPlanChapterId()+"EndWordId或BeginWordId不能为空", null);
					}
					if (pc.getBeginWordId()>pc.getEndWordId()){
						return Message(ERROR, "对应ID:"+pc.getPlanChapterId()+"BeginWordId不能大于EndWordId", null);
					}
					PlanChapterService.savePlanChapter(pc);
				}
			}else if (type.equals("coinsConfig")){
				List<CoinsVo> ls = util.bindToModels(CoinsVo.class, false);
				for (CoinsVo c: ls){
					if (c.getId()<=0){
						continue;
					}
					if(null == c.getIcon()){
						return Message(ERROR, "充值配置Icon不能为空", null);
					}
					coinsService.saveCoins(c);
				}
			}else {
				return Message(ERROR, "所传文件类型错误", null);
			}
			logs.setType(type);
			uploadLogsService.save(logs);   //上传日志存储
			return Message(SUCCESS, "上传成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e,"上传异常");
		}
	}
	/**
	 * 资源文件上传
	 * @param req
	 * @param resp
	 * @param file
	 * @param versionCode
	 * @return
	 */
	@RequestMapping("resourceUpload")
	@ResponseBody
	public JSON resourceUpload(HttpServletRequest req, HttpServletResponse resp,MultipartFile file,String versionCode){
		String fileName = file.getOriginalFilename();
		//UploadLogsVo logs = new UploadLogsVo(OtherUtils.getCurrentDate(),fileName,reName,"",reName);
		UploadLogsVo logs = new UploadLogsVo();
		String date = OtherUtils.getCurrentDate();
		logs.setUploadDate(date);
		logs.setFileName(fileName);
		logs.setRelName(fileName);
		logs.setType("");
		logs.setPath(fileName);		
		String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
		String type = "";
		if (isEmpty(suffix)){
			return Message(ERROR, "请上传正确格式文件（图片文件：jpg、gif、png或音频文件：MP3、OGG、WMA、WAV、APE等）", null);
		}
		if (isEmpty(versionCode)||versionCode.equals("0")){
			return Message(ERROR, "请选择版本号", null);
		}
		if (suffix.equals("jpg")||suffix.equals("gif")||suffix.equals("png")){
			type="图片";
		} else if (suffix.equals("mp3")||suffix.equals("ogg")||suffix.equals("wma")||suffix.equals("wav")||suffix.equals("ape")){
			type = "音频";
		} else {
			return Message(ERROR, "请上传正确格式文件（图片文件：jpg、gif、png或音频文件：MP3、OGG、WMA、WAV、APE）", null);
		}
		try {
			oss.putObject(bucket, fileName, file.getInputStream());
			ResourceVo rv = new ResourceVo();
			rv.setFileName(fileName);
			rv.setOssKey(fileName);
			rv.setType(type);
			rv.setUploadDate(date);
			rv.setVsersionCode(versionCode);
			resourceService.saveResource(rv);
			return Message(SUCCESS, "上传成功", null);
		} catch (IOException e) {
			LoggerUtil.logInfo(e, "上传oss失败");
		}
		return null;
	}
	
	/**
	 *  打包解析后数据，生成对应json文件上传OSS
	 * @param req
	 * @param resp
	 * @param pub
	 * @return
	 */
	@RequestMapping("/publish")
	@ResponseBody
	public JSON publishLogs(HttpServletRequest req, HttpServletResponse resp, PublishLogsVo pub){
		try {
			int total = 0;
			String versionCode =OtherUtils.UuidUtils();
			if (req.getSession().getAttribute("Back_user")==null||req.getSession().getAttribute("Back_user").equals("")){
				return Message(ERROR, "登录失效，请重新登录后操作", null);
			}
			String userName = (String)((BackUserVo) req.getSession().getAttribute("Back_user")).getTel(); //生成相关打包信息（日志）
			pub.setPublishDate(OtherUtils.getCurrentDate());
			pub.setPubUser(userName);
			pub.setVersionCode(versionCode);
			pub.setStatus("3");   //设置状态码 3：预更新版本
			List<BookConfigVo> books = bookServcie.getBookConfigList();    //打包文件按书为单位，依次打包上传
			if (books.isEmpty()){
				return Message(ERROR, "请检查典籍配置是否正确", null);
			} else {
				String file = null;
				String file2 = null;
				for (BookConfigVo bk:books){     //查找对应书籍
					InputStream newFile = null;
					BookConfig bookConfigs = new BookConfig(bk.getBookId(),bk.getBookName(),
							bk.getWriter(),bk.getReader(),bk.getBeginChapterId(),bk.getEndChapterId(),
							bk.getBeginPlanId(),bk.getEndPlanId());
					List<ChapterConfigVo> chapters = chapterService.getChapterConfigList(bk.getBeginChapterId(),bk.getEndChapterId());
					List<ChapterConfig> afterChap = new ArrayList<ChapterConfig>();
					List<PlanConfigVo> planConfigs = planConfigService.getPlanConfigListByPlan(bk.getBeginPlanId(),bk.getEndPlanId());
					if (planConfigs.isEmpty()){
						return Message(ERROR, "请检查典籍及计划配置是否正确", null);
					} else {
					List<PlanConfigVo>	planConfigList = new ArrayList<PlanConfigVo>();
						for(PlanConfigVo pc:planConfigs){
							List<PlanChapterConfigVo> pccv = PlanChapterService.getPlanChapterById(pc.getPlanChapterdx(),pc.getPlanChapterdy());
							if(pccv.size()==0){
								return Message(ERROR, "请检查计划章节配置，以及计划配置起始章节id是否正确-错误编号"+pc.getPlanChapterdx()+"--"+pc.getPlanChapterdy(), null);
							}
							PlanConfig planConfig = new PlanConfig(pc.getPlanId(), pc.getPlanName(), pc.getPlanTitle(), 
									pc.getPlanType(), pc.getCount(),pccv.get(0).getBeginWordId(),pccv.get(pccv.size()-1).getEndWordId()
									,pc.getFirstMedal(),pc.getFirstExp(),pc.getMedal(),pc.getExp());
							List<RecordConfigVo> rc = new ArrayList<RecordConfigVo>();
							List<ExplainConfigVo> ec = new ArrayList<ExplainConfigVo>();
							for(PlanChapterConfigVo pcvv:pccv){
								List<RecordConfigVo> sc = recordServcie.getRecordConfigList(pcvv.getBeginWordId(), pcvv.getEndWordId());
								List<ExplainConfigVo> exc = explainService.getExplainConfigList(sc.get(0).getExplainId(), sc.get(sc.size()-1).getExplainId());
								rc.addAll(sc);
								ec.addAll(exc);
							}
							try {
								ec = ExplainUtil(ec);
							} catch (Exception e) {
								return LoggerUtil.logInfo(e,"计划分词失败");
							}
							planConfig.setExplains(ec);
						    planConfig.setSentence(rc);
						    planConfigList.add(planConfig);
						}
						bookConfigs.setPlanConfigs(planConfigList);
					}
					if (chapters.isEmpty()){
						return Message(ERROR, "请检查章节配置是否正确", null);
					} else {
						List<RecordConfigVo> records = null;
						List<ExplainConfigVo> explain = null;
						List<ExplainConfig> explains = null;
						for (ChapterConfigVo cc:chapters){  //查找对应章节
							ChapterConfig chapter = new ChapterConfig(cc.getChapterId(),cc.getChapterName()
									,cc.getBeginWordId(),cc.getEndWordId());
							 records = recordServcie.getRecordConfigList(cc.getBeginWordId(),cc.getEndWordId());
							if (!records.isEmpty()){    //对应录音配置
								int begin,end = 0;
								try {
									begin = records.get(0).getExplainId();
									end = records.get(records.size()-1).getExplainId();
								} catch (Exception e) {
									return LoggerUtil.logInfo(e,"请检查录音配置是否符合格式");
								}
								explain = explainService.getExplainConfigList(begin,end); //对应释义配置
								explains = new ArrayList<ExplainConfig>();
								if (!explain.isEmpty()){
									for (ExplainConfigVo ec:explain){ 
										ExplainConfig expc = new ExplainConfig(ec.getExplainId(),ec.getWord()
												,ec.getPhoneticize(),ec.getStoryId1(),ec.getStoryId2(),
												ec.getStoryId3(),ec.getStoryId4(),ec.getWordExplain());
										List<String> words = new ArrayList<String>();
										List<String> phoneticizes = new ArrayList<String>();
										try {
											Collections.addAll(words, ec.getWord().split("_"));
											Collections.addAll(phoneticizes, ec.getPhoneticize().split("_"));
										} catch (Exception e) {
											return LoggerUtil.logInfo(e,"请释义配置是否符合格式");
										}
										expc.setPhoneticizes(phoneticizes);
										expc.setWords(words);
										List<StoryConfigVo> storys = new ArrayList<StoryConfigVo>();  //对应故事
										if(ec.getStoryId1()!=0){
											StoryConfigVo story1 = storyConfigService.getStory(ec.getStoryId1()); 
											if (story1==null){
												return Message(ERROR, "请检查故事配置", null);
											}
											storys.add(story1);
											if (ec.getStoryId2()!=0){
												StoryConfigVo story2 = storyConfigService.getStory(ec.getStoryId2());
												if (story2==null){
													return Message(ERROR, "请检查故事配置", null);
												}
												storys.add(story2);
												if (ec.getStoryId3()!=0){
													StoryConfigVo story3 = storyConfigService.getStory(ec.getStoryId3());
													if (story3==null){
														return Message(ERROR, "请检查故事配置", null);
													}
													storys.add(story3);
													if (ec.getStoryId4()!=0){
														StoryConfigVo story4 = storyConfigService.getStory(ec.getStoryId4());
														if (story4==null){
															return Message(ERROR, "请检查故事配置", null);
														}
														storys.add(story4);
													}
												}
											}
										}
										expc.setStorys(storys);
										explains.add(expc);
									}
								} 
							} else {
								return Message(ERROR, "请检录音及章节配置是否关联正确", null);
							}
							chapter.setExplain(explains);
							chapter.setSentence(records);
							afterChap.add(chapter);
							file = records.get(1).getFile();
							file2 = records.get(1).getFile2();
						}
					}
					bookConfigs.setChapters(afterChap);
					String key = OtherUtils.UuidUtils().substring(15,31);
					UpdateTableVo update = null;
					String md5Code = "";
					try {          
						//指定版本号上传OSS,同时查询上个版本书籍文本是否有所变动，无变动则不做更新
						PublishLogsVo pl = publishService.getPublishByStatus("4");//状态码为4 的上个版本
						newFile =  new ByteArrayInputStream(JSON.toJSONString(bookConfigs,SerializerFeature.WriteMapNullValue).getBytes());
						md5Code = MD5Util.getStringHash(JSON.toJSONString(bookConfigs,SerializerFeature.WriteMapNullValue));
						int size = newFile.available()/1024;
						if (pl!=null){
							UpdateTableVo ut = updateService.getUpdateTableByVersionCodeAndBookName(pl.getVersionCode(), bk.getBookName());//按版本号及书名获取对应上个版本书籍信息
							if(ut!=null&&md5Code.equals(ut.getMd5Code())){//MDS验证文本内容一致性
								//update = new UpdateTable(OtherUtils.UuidUtils(),bk.getBookId(),ut.getKeyAndType(),bk.getBookName(),file2,file,versionCode,ut.getSize());
								update = new UpdateTableVo();
								update.setBookId(bk.getBookId());
								update.setBookName(bk.getBookName());
								update.setKeyAndType(ut.getKeyAndType());
								update.setFileKey(file);
								update.setFileKey2(file2);
								update.setVersionCode(versionCode);
								update.setMd5Code(md5Code);
								update.setSize(ut.getSize());
								total = total+ut.getSize();
							} else {
								size = newFile.available()/1024;
//								update = new UpdateTable(OtherUtils.UuidUtils(),bk.getBookId(),key+".json",bk.getBookName(),file2,file,versionCode,size);
								update = new UpdateTableVo();
								update.setBookId(bk.getBookId());
								update.setBookName(bk.getBookName());
								update.setKeyAndType(key+".json");
								update.setFileKey(file);
								update.setFileKey2(file2);
								update.setVersionCode(versionCode);
								update.setMd5Code(md5Code);
								update.setSize(size);
								total =total+size;
								oss.putObject(bucket, key+".json",newFile);
							}
						} else {
							size = newFile.available()/1024;
//							update = new UpdateTable(OtherUtils.UuidUtils(),bk.getBookId(),key+".json",bk.getBookName(),file2,file,versionCode,size);
							update = new UpdateTableVo();
							update.setBookId(bk.getBookId());
							update.setBookName(bk.getBookName());
							update.setKeyAndType(key+".json");
							update.setFileKey(file);
							update.setFileKey2(file2);
							update.setVersionCode(versionCode);
							update.setMd5Code(md5Code);
							update.setSize(size);
							total =total+size;
							oss.putObject(bucket, key+".json",newFile);
						}
					} catch (Exception e) {
						return LoggerUtil.logInfo(e,"提交云存储失败");
					} finally {
						newFile.close();
					}
					updateService.saveUpdate(update); //记录相关操作日志
				}
				pub.setSize(total);
				publishService.savePublishLogs(pub);
				return Message(SUCCESS, "打包成功", null);
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e,"打包失败");
		}	
	}
	//分词，查找对应故事工具类方法
	public List<ExplainConfigVo> ExplainUtil(List<ExplainConfigVo> explain){
		List<ExplainConfigVo> explains = new ArrayList<ExplainConfigVo>();
		for (ExplainConfigVo ec:explain){  
			ExplainConfig exp = new ExplainConfig(ec.getExplainId(),ec.getWord(),ec.getPhoneticize(), 
					ec.getStoryId1(),ec.getStoryId2(), ec.getStoryId3(), ec.getStoryId4(),ec.getWordExplain());
			List<String> words = new ArrayList<String>();
			List<String> phoneticizes = new ArrayList<String>();
			Collections.addAll(words, ec.getWord().split("_"));
			Collections.addAll(phoneticizes, ec.getPhoneticize().split("_"));
			exp.setPhoneticizes(phoneticizes);
			exp.setWords(words);
			exp.setWord(null);
			exp.setPhoneticize(null);
			List<StoryConfigVo> storys = new ArrayList<StoryConfigVo>();  //对应故事
			if(ec.getStoryId1()!=0){
				StoryConfigVo story1 = storyConfigService.getStory(ec.getStoryId1());  
				storys.add(story1);
				if (ec.getStoryId2()!=0){
					StoryConfigVo story2 = storyConfigService.getStory(ec.getStoryId2());
					storys.add(story2);
					if (ec.getStoryId3()!=0){
						StoryConfigVo story3 = storyConfigService.getStory(ec.getStoryId3());
						storys.add(story3);
						if (ec.getStoryId4()!=0){
							StoryConfigVo story4 = storyConfigService.getStory(ec.getStoryId4());
							storys.add(story4);
						}
					}
				}
			}
			exp.setStorys(storys);
			explains.add(exp);
		}
		return explains;
	}
	
	public JSON getConfigResource(HttpServletRequest req, HttpServletResponse resp, PublishLogsVo pub){
		String versionCode =OtherUtils.UuidUtils();
		String userName = (String)((BackUserVo) req.getSession().getAttribute("Back_user")).getTel(); //生成相关打包信息（日志）
		pub.setPublishDate(OtherUtils.getCurrentDate());
		pub.setPubUser(userName);
		pub.setVersionCode(versionCode);
		pub.setStatus("3");   //设置状态码 3：预更新版本
		List<BookConfigVo> bookConfig = bookServcie.getBookConfigList();
		List<ChapterConfigVo> chapterConfig = chapterService.getChapterConfigList();
		List<RecordConfigVo> recordConfig = recordServcie.getRecordConfigList();
		List<PlanConfigVo> planConfig = planConfigService.getPlanConfigList();
		List<PlanChapterConfigVo> planChapterConfig  = PlanChapterService.getPlanChapterList();
		List<ExplainConfigVo> explainConfig = explainService.getExplainConfigList();
		List<ExpertReadingVo> expertReading = expertService.getExpertReadingList();
		List<StoryConfigVo> storyConfig = storyConfigService.getStoryConfigList();
		if (bookConfig==null||bookConfig.isEmpty()){
			return Message(ERROR, "典籍配置未上传，请上传后打包", null);
		}
		if (chapterConfig==null||chapterConfig.isEmpty()){
			return Message(ERROR, "章节配置未上传，请上传后打包", null);
		}
		if (recordConfig==null||recordConfig.isEmpty()){
			return Message(ERROR, "录音进度未上传，请上传后打包", null);
		}
		if (planConfig==null||planConfig.isEmpty()){
			return Message(ERROR, "计划配置未上传，请上传后打包", null);
		}
		if (planChapterConfig==null||planChapterConfig.isEmpty()){
			return Message(ERROR, "计划章节配置未上传，请上传后打包", null);
		}
		if (explainConfig==null||explainConfig.isEmpty()){
			return Message(ERROR, "释义配置未上传，请上传后打包", null);
		}
		if (expertReading==null||expertReading.isEmpty()){
			return Message(ERROR, "佳作配置未上传，请上传后打包", null);
		}		
		if (storyConfig==null||storyConfig.isEmpty()){
			return Message(ERROR, "故事配置未上传，请上传后打包", null);
		}
		JSONObject obj = new JSONObject();
		obj.put("book", bookConfig);
		obj.put("chapter", chapterConfig);
		obj.put("record", recordConfig);
		obj.put("plan",planConfig);
		obj.put("planChapter", planChapterConfig);
		obj.put("explain", explainConfig);
		obj.put("expert", expertReading);
		obj.put("story", storyConfig);
		InputStream file = null;
		file =  new ByteArrayInputStream(JSON.toJSONString(obj,SerializerFeature.WriteMapNullValue).getBytes());
		oss.putObject(bucket, versionCode,file);
		try {
			int c = file.available()/1024;
		} catch (IOException e) {
			LoggerUtil.logInfo(e, "打包异常，程序员的锅");
		} finally {
			try {
				file.close();
			} catch (IOException e) {
				LoggerUtil.logInfo(e, "打包异常，程序员的锅");
			}
		}
		return Message(SUCCESS, "发布成功", null);
	}
	
	/**
	 *  静态资源文件上传
	 * @param req
	 * @param resp
	 * @param file
	 * 			上传静态资源文件
	 * @param type
	 * 			文件类型 1:音频
	 * @return
	 */
	@RequestMapping("/ossUpload")
	@ResponseBody
	public JSON ossUpload(HttpServletRequest req, HttpServletResponse resp, MultipartFile file, String type, String versionCode){
		if (isEmpty(versionCode)){
			return Message(ERROR, "未提交版本号", null);
		}
		if (isEmpty(type)){
			return Message(ERROR, "未指定文件类型", null);
		}
		String fileName = file.getOriginalFilename(); //获取文件真实名
		String key = OtherUtils.UuidUtils();
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		try {
			oss.putObject(bucket, key+"."+suffix, file.getInputStream());//上传OSS
		} catch (IOException e) {
			LoggerUtil.logInfo(e, "上传失败");
		} 
		ResourceVo rv = new ResourceVo();
		rv.setOssKey(key+"."+suffix);
		rv.setUploadDate(OtherUtils.getCurrentDate());
		rv.setType(type);
		rv.setFileName(fileName);
		resourceService.saveResource(rv);
		return Message(SUCCESS, "上传成功", null);
	}
	/**
	 * 获取版本对应文件列表
	 * @param req
	 * @param resp
	 * @param versionCode
	 * @return
	 */
	@RequestMapping("/getFilesByVersionCode")
	@ResponseBody
	public JSON getFilesByVersionCode(HttpServletRequest req, HttpServletResponse resp,String versionCode){
		if (isEmpty(versionCode)){
			return Message(SUCCESS, " 未提交版本码暂无数据", null);
		}
		List<ResourceVo> rvs = resourceService.getResourceByVersionCode(versionCode);
		return Message(SUCCESS, "获取数据", rvs);
	}
	/**
	 * 获取版本列表
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/getVersionCode")
	@ResponseBody
	public JSON getVersionCode(HttpServletRequest req, HttpServletResponse resp){
		List<PublishLogsVo> plvs = publishService.getPublishLogs();
		return Message(SUCCESS, "获取版本号", plvs);
	}
}
